package edu.inf3.j2ee.framework;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class dbMySQL implements IDatabase {
	
	private String dbHostname;
	private String dbName;
	private String dbUsername;
	private String dbPassword;

	private Connection connection;
	private Statement statement;
	private ResultSet resultset;
	
	private boolean isConnected;
	
	public dbMySQL (String host, String db, String user, String pwd){
		this.dbHostname = host;
		this.dbName = db;
		this.dbUsername = user;
		this.dbPassword = pwd;
		this.isConnected = false;
	}

	@Override
	public void connect() throws InstantiationException, IllegalAccessException,
						ClassNotFoundException, SQLException{
		
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			this.connection = DriverManager.getConnection("jdbc:mysql://" + this.dbHostname
														  + "/" + this.dbName
					 									  + "?user=" + this.dbUsername
					 									  + "&password=" + this.dbPassword);
			this.isConnected = true;
	}

	@Override
	public void disconnect() {
		if (this.isConnected){
			try {
				this.connection.close();
			} catch (SQLException e) {
				;
			}finally{
				this.isConnected = false;
			}
		}

	}

	@Override
	public void execQuery(String Query) throws SQLException {

			this.statement = this.connection.createStatement();
			if (this.statement.execute(Query)){
				this.resultset = this.statement.getResultSet();
			}
	}

	@Override
	public boolean getBool(String column) throws SQLException {
		
		return (this.resultset.getBoolean(column));
	}

	@Override
	public double getDouble(String column) throws SQLException {
		
		return (this.resultset.getDouble(column));
	}

	@Override
	public int getInt(String column) throws SQLException {
		
		return (this.resultset.getInt(column));
	}

	@Override
	public String getString(String column) throws SQLException {
		return (this.resultset.getString(column));
	}

	@Override
	public boolean nextRecord() throws SQLException {
		return (this.resultset.next());
	}

	@Override
	public void clearResources() throws SQLException {
		if (this.statement != null){
			this.statement.close();
		}
		if (this.resultset != null){
			this.resultset.close();
		}

	}

	@Override
	public boolean lockTable(String tbName) throws SQLException {
		
		return true;
	}

	@Override
	public boolean unlockTable(String tbName)throws SQLException  {
		
		return true;
	}
	

}
